//
//  HomeController.swift
//  ExpressDriver
//
//  Created by sheng on 2017/11/7.
//  Copyright © 2017年 sheng. All rights reserved.
//

import UIKit
import SnapKit
import SlideMenuControllerSwift
import Charts

class HomeController: UIViewController,IAxisValueFormatter, IValueFormatter {
    
    var scrollView: UIScrollView!
    
    var currentJob: MenuButton!
    
    var outStanding: MenuButton!
    
    var orderTrack: MenuButton!
    
    var historyBtn: MenuButton!
    
    var barChart: BarChartView!
    
    var pieChartView: PieChartView!
    
    var line1: UIView!
    
    var currentDateLabel: UILabel!
    
    var dateTypeLabel: UILabel!
    
    var frequencyLabel: UILabel!
    
    var selectDateLabel: UILabel!
    
    var selectFreqyencyLabel: UILabel!
    
    var fromLabel: UILabel!
    
    var toLabel: UILabel!
    
    var startDateLabel: UILabel!
    
    var startDateBtn: UIButton!
    
    var endDateLabel: UILabel!
    
    var endDateBtn: UIButton!
    
    var barChart2: BarChartView!
    
    var pieChartView2: PieChartView!
    
    var titles: [String]?
    
    var titles2: [String]?
    
    var colors = [UIColor.init(red: 142/255.0, green: 189/255.0, blue: 255/255.0, alpha: 1.0),
                  
                  UIColor.init(red: 255/255.0, green: 86/255.0, blue: 101/255.0, alpha: 1.0),
                  
                  UIColor.init(red: 0/255.0, green: 211/255.0, blue: 189/255.0, alpha: 1.0)]
    
    let statusHeight = UIApplication.shared.statusBarFrame.height
    let scrrenHeight = UIScreen.main.bounds.height
    let scrrenWidth = UIScreen.main.bounds.width
    
    let dateType:[String] = ["Pickup Date","Delivery Date","Repaire Date","Booking Date"]
    let freuqency:[String] = ["Weekly","Monthly","Yearly"]
    

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.done, target: self, action: #selector(openMenu))
        setUI()
    }
    
    
    func setUI() {
        
        scrollView = UIScrollView()
        scrollView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
        scrollView.contentSize.width = scrrenWidth
        scrollView.isScrollEnabled = true
        scrollView.showsVerticalScrollIndicator = true
        scrollView.indicatorStyle = .black
        scrollView.alwaysBounceVertical = true
        scrollView.alwaysBounceHorizontal = false
        self.view.addSubview(scrollView)
        
        currentJob = MenuButton()
        currentJob.setTitle("Current Job", for:UIControlState.normal)
        currentJob.setImage(UIImage(named:"page"),for:.normal)
        currentJob.addTarget(self, action: #selector(jumpToCurrentJob), for: .touchUpInside)
        scrollView.addSubview(currentJob)
        currentJob.snp.makeConstraints { (make) in
            make.top.equalTo(scrollView.snp.top).offset(15)
            make.width.equalTo(scrrenWidth/2)
            make.height.equalTo(75)
        }
        
        
        outStanding = MenuButton()
        outStanding.setTitle("Outstanging Job", for:UIControlState.normal)
        outStanding.setImage(UIImage(named:"page"),for:.normal)
        outStanding.addTarget(self, action: #selector(jumpToOutstangdingJob), for: .touchUpInside)
        scrollView.addSubview(outStanding)
        outStanding.snp.makeConstraints { (make) in
            make.top.equalTo(scrollView.snp.top).offset(15)
            make.left.equalTo(currentJob.snp.right)
            make.width.equalTo(scrrenWidth/2)
            make.height.equalTo(75)
        }
        
        
        orderTrack = MenuButton()
        orderTrack.setTitle("Order Tracking", for:UIControlState.normal)
        orderTrack.setImage(UIImage(named:"search"),for:.normal)
        orderTrack.addTarget(self, action: #selector(jumpToTrack), for: .touchUpInside)
        scrollView.addSubview(orderTrack)
        orderTrack.snp.makeConstraints { (make) in
            make.top.equalTo(currentJob.snp.bottom).offset(10)
            make.width.equalTo(scrrenWidth/2)
            make.height.equalTo(75)
        }
        
        historyBtn = MenuButton()
        historyBtn.setTitle("History", for:UIControlState.normal)
        historyBtn.addTarget(self, action: #selector(jumpToHistory), for: .touchUpInside)
        historyBtn.setImage(UIImage(named:"history"),for:.normal)
        scrollView.addSubview(historyBtn)
        historyBtn.snp.makeConstraints { (make) in
            make.top.equalTo(outStanding.snp.bottom).offset(10)
            make.left.equalTo(orderTrack.snp.right)
            make.width.equalTo(scrrenWidth/2)
            make.height.equalTo(75)
        }
        
        
        line1 =  UIView()
        line1.backgroundColor = UIColor.lightGray
        scrollView.addSubview(line1)
        line1.snp.makeConstraints { (make) in
            make.top.equalTo((historyBtn?.snp.bottom)!).offset(0)
            make.height.equalTo(0.5)
            make.left.equalTo(10)
            make.right.equalTo(-10)
            make.centerX.equalTo(self.view)
        }
        
        currentDateLabel = UILabel()
        currentDateLabel.text = "2017-11-20(Current Date)"
        currentDateLabel.textColor = UIColor.black
        currentDateLabel.font = UIFont.systemFont(ofSize: 14)
        scrollView.addSubview(currentDateLabel)
        currentDateLabel.snp.makeConstraints { (make) in
            make.top.equalTo(line1.snp.bottom).offset(10)
            make.centerX.equalTo(self.view)
        }
        
        setCharts()
        
        
        pieChartView = PieChartView()
        pieChartView.backgroundColor = UIColor.white
        scrollView.addSubview(pieChartView)
        pieChartView.snp.makeConstraints { (make) in
            make.top.equalTo(barChart.snp.bottom).offset(15)
            make.left.equalTo(15)
            make.right.equalTo(-15)
            make.centerX.equalTo(self.view)
            make.width.equalTo(scrrenWidth)
            make.height.equalTo(250)
        }
        let title: [String] = ["delivery","signature","complete"]
        let datas: [Double]   = [1500,900,1050]
        setPieChart(dataPoints: title, values: datas, pieChart: pieChartView)
        
        
        dateTypeLabel = UILabel()
        dateTypeLabel.text = "Date Type"
        dateTypeLabel.font = UIFont.systemFont(ofSize: 13)
        dateTypeLabel.textColor = UIColor.black
        scrollView.addSubview(dateTypeLabel)
        dateTypeLabel.snp.makeConstraints { (make) in
            make.top.equalTo(pieChartView.snp.bottom).offset(10)
            make.left.equalTo(15)
        }
        
        selectDateLabel = UILabel()
        selectDateLabel.text = "Pickup Date"
        selectDateLabel.backgroundColor = UIColor.white
        selectDateLabel.layer.borderColor = UIColor.lightGray.cgColor
        selectDateLabel.layer.borderWidth = 0.5
        selectDateLabel.layer.cornerRadius = 4
        selectDateLabel.textAlignment = .center
        selectDateLabel.font = UIFont.systemFont(ofSize: 13)
        selectDateLabel.textColor = UIColor.black
        let dateTap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(showDateType))
        selectDateLabel.addGestureRecognizer(dateTap)
        //设置能否与用户进行交互 默认是NO
        selectDateLabel.isUserInteractionEnabled = true
        scrollView.addSubview(selectDateLabel)
        selectDateLabel.snp.makeConstraints { (make) in
            make.top.equalTo(dateTypeLabel.snp.bottom).offset(5)
            make.left.equalTo(15)
            make.width.equalTo((scrrenWidth - 95) / 2)
            make.height.equalTo(25)
        }
        
        
        selectFreqyencyLabel = UILabel()
        selectFreqyencyLabel.text = "Weekly"
        selectFreqyencyLabel.backgroundColor = UIColor.white
        selectFreqyencyLabel.layer.borderColor = UIColor.lightGray.cgColor
        selectFreqyencyLabel.layer.borderWidth = 0.5
        selectFreqyencyLabel.layer.cornerRadius = 4
        selectFreqyencyLabel.textAlignment = .center
        selectFreqyencyLabel.font = UIFont.systemFont(ofSize: 13)
        selectFreqyencyLabel.textColor = UIColor.black
        let freuqencyTap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(showFreuqencyType))
        selectFreqyencyLabel.addGestureRecognizer(freuqencyTap)
        //设置能否与用户进行交互 默认是NO
        selectFreqyencyLabel.isUserInteractionEnabled = true
        scrollView.addSubview(selectFreqyencyLabel)
        selectFreqyencyLabel.snp.makeConstraints { (make) in
            make.top.equalTo(selectDateLabel.snp.top)
            make.right.equalTo(-15)
            make.width.equalTo((scrrenWidth - 95) / 2)
            make.height.equalTo(25)
        }
        
        
        frequencyLabel = UILabel()
        frequencyLabel.text = "Frequency"
        frequencyLabel.font = UIFont.systemFont(ofSize: 13)
        frequencyLabel.textColor = UIColor.black
        scrollView.addSubview(frequencyLabel)
        frequencyLabel.snp.makeConstraints { (make) in
            make.top.equalTo(pieChartView.snp.bottom).offset(10)
            make.left.equalTo(selectFreqyencyLabel.snp.left)
        }
        
        
        fromLabel = UILabel()
        fromLabel.text = "From"
        fromLabel.font = UIFont.systemFont(ofSize: 13)
        fromLabel.textColor = UIColor.black
        scrollView.addSubview(fromLabel)
        fromLabel.snp.makeConstraints { (make) in
            make.top.equalTo(selectDateLabel.snp.bottom).offset(10)
            make.left.equalTo(15)
        }
        
        toLabel = UILabel()
        toLabel.text = "To"
        toLabel.font = UIFont.systemFont(ofSize: 13)
        toLabel.textColor = UIColor.black
        scrollView.addSubview(toLabel)
        
        
        startDateLabel = UILabel()
        startDateLabel.text = "2017-11-21"
        startDateLabel.backgroundColor = UIColor.white
        startDateLabel.layer.borderColor = UIColor.lightGray.cgColor
        startDateLabel.layer.borderWidth = 0.5
        startDateLabel.layer.cornerRadius = 4
        startDateLabel.textAlignment = .center
        startDateLabel.font = UIFont.systemFont(ofSize: 13)
        startDateLabel.textColor = UIColor.black
        scrollView.addSubview(startDateLabel)
        startDateLabel.snp.makeConstraints { (make) in
            make.top.equalTo(fromLabel.snp.bottom).offset(5)
            make.left.equalTo(15)
            make.width.equalTo((scrrenWidth - 105) / 2)
            make.height.equalTo(25)
        }
        
        
        
        startDateBtn = UIButton()
        let startImage = UIImage(named:"calendar")?.withRenderingMode(.alwaysOriginal)
        startDateBtn.setImage(startImage, for:.normal)
        startDateBtn.adjustsImageWhenHighlighted = false
        startDateBtn.addTarget(self, action: #selector(selectStartDate), for: .touchUpInside)
        scrollView.addSubview(startDateBtn)
        startDateBtn.snp.makeConstraints { (make) in
            make.left.equalTo(startDateLabel.snp.right).offset(5)
            make.height.width.equalTo(25)
            make.centerY.equalTo(startDateLabel.snp.centerY)
        }
        
        
        endDateBtn = UIButton()
        let endImage = UIImage(named:"calendar")?.withRenderingMode(.alwaysOriginal)
        endDateBtn.setImage(endImage, for:.normal)
        endDateBtn.adjustsImageWhenHighlighted = false
        endDateBtn.addTarget(self, action: #selector(selectEndDate), for: .touchUpInside)
        scrollView.addSubview(endDateBtn)
        endDateBtn.snp.makeConstraints { (make) in
            make.right.equalTo(-15)
            make.height.width.equalTo(25)
            make.centerY.equalTo(startDateBtn.snp.centerY)
        }
        
        endDateLabel = UILabel()
        endDateLabel.text = "2017-11-22"
        endDateLabel.backgroundColor = UIColor.white
        endDateLabel.layer.borderColor = UIColor.lightGray.cgColor
        endDateLabel.layer.borderWidth = 0.5
        endDateLabel.layer.cornerRadius = 4
        endDateLabel.textAlignment = .center
        endDateLabel.font = UIFont.systemFont(ofSize: 13)
        endDateLabel.textColor = UIColor.black
        scrollView.addSubview(endDateLabel)
        endDateLabel.snp.makeConstraints { (make) in
            make.right.equalTo(endDateBtn.snp.left).offset(-5)
            make.width.equalTo((scrrenWidth - 105) / 2)
            make.height.equalTo(25)
            make.centerY.equalTo(endDateBtn.snp.centerY)
        }
        
        toLabel.snp.makeConstraints { (make) in
            make.left.equalTo(endDateLabel.snp.left)
            make.top.equalTo(selectFreqyencyLabel.snp.bottom).offset(10)
        }
        
        
        barChart2 = BarChartView.init(frame: CGRect.init(x: 0, y: 0, width: scrrenWidth, height: 300))
        barChart2.backgroundColor = UIColor.white
        
        scrollView.addSubview(barChart2)
        barChart2.snp.makeConstraints { (make) in
            make.top.equalTo(endDateLabel.snp.bottom).offset(10)
            make.left.equalTo(15)
            make.right.equalTo(-15)
            make.centerX.equalTo(self.view)
            make.width.equalTo(scrrenWidth)
            make.height.equalTo(250)
        }
        
        setBarChart(chartView: barChart2)
        titles2 = ["start","delivery","signature","complete"]
        let datas2: [Double]   = [1250,1500,915,1050]
        setBarChartData(titleData: titles!, datas: datas2, chartView: barChart2)
        
        
        
        pieChartView2 = PieChartView()
        pieChartView2.backgroundColor = UIColor.white
        scrollView.addSubview(pieChartView2)
        pieChartView2.snp.makeConstraints { (make) in
            make.top.equalTo(barChart2.snp.bottom).offset(15)
            make.left.equalTo(15)
            make.right.equalTo(-15)
            make.centerX.equalTo(self.view)
            make.width.equalTo(scrrenWidth)
            make.height.equalTo(250)
        }
        let pieTitle: [String] = ["delivery","signature","complete"]
        let pieDatas: [Double]   = [1500,900,1050]
        setPieChart(dataPoints: pieTitle, values: pieDatas, pieChart: pieChartView2)
        
        
    }
    
    
    func showDateType(sender: UILabel) {
        let alertController : UIAlertController = UIAlertController.init(title:nil, message: nil, preferredStyle: .actionSheet)
        
        for i in 0..<dateType.count {
            
            let btn = UIAlertAction(title: dateType[i], style: .default) { (UIAlertAction) -> Void in
                print(UIAlertAction.title!); // 打印选中内容
                self.selectDateLabel.text = UIAlertAction.title!
            }
            alertController.addAction(btn);
        }
        let cleanAction = UIAlertAction(title: "cancel", style: UIAlertActionStyle.cancel,handler:nil)
        alertController.addAction(cleanAction);
        self.present(alertController, animated: true, completion: nil)
    }
    
    
    func showFreuqencyType(sender: UILabel) {
        let alertController : UIAlertController = UIAlertController.init(title:nil, message: nil, preferredStyle: .actionSheet)
        
        for i in 0..<freuqency.count {
            let btn = UIAlertAction(title: freuqency[i], style: .default) { (UIAlertAction) -> Void in
                print(UIAlertAction.title!); // 打印选中内容
                self.selectFreqyencyLabel.text = UIAlertAction.title!
            }
            alertController.addAction(btn);
        }
        let cleanAction = UIAlertAction(title: "cancel", style: UIAlertActionStyle.cancel,handler:nil)
        alertController.addAction(cleanAction);
        self.present(alertController, animated: true, completion: nil)
    }
    
    
    func selectEndDate(_ sender: UIButton) {
        let alertController:UIAlertController=UIAlertController(title: "\n\n\n\n\n\n\n\n\n\n\n\n", message: nil, preferredStyle: UIAlertControllerStyle.actionSheet)
        // 初始化 datePicker
        let datePicker = UIDatePicker( )
        //datePicker.locale = NSLocale(localeIdentifier: "zh_CN") as Locale
        // 设置样式，当前设为同时显示日期和时间
        datePicker.datePickerMode = UIDatePickerMode.date
        // 设置默认时间
        datePicker.date = NSDate() as Date
        datePicker.frame = CGRect(x: 0, y: 0, width: alertController.view.bounds.size.width, height: 230)
        alertController.addAction(UIAlertAction(title: "determine", style: UIAlertActionStyle.default){
            (alertAction)->Void in
            
            let dformatter = DateFormatter()
            dformatter.dateFormat = "yyyy-MM-dd"
            // 使用日期格式器格式化日期、时间
            let datestr = dformatter.string(from: datePicker.date)
            self.endDateLabel.text = datestr
            print("date select: \(datestr)")
        })
        alertController.addAction(UIAlertAction(title: "cancel", style: UIAlertActionStyle.cancel,handler:nil))
        
        alertController.view.addSubview(datePicker)
        
        self.present(alertController, animated: true, completion: nil)
    }
    
    
    
    func selectStartDate(_ sender: UIButton) {
        let alertController:UIAlertController=UIAlertController(title: "\n\n\n\n\n\n\n\n\n\n\n\n", message: nil, preferredStyle: UIAlertControllerStyle.actionSheet)
        // 初始化 datePicker
        let datePicker = UIDatePicker( )
        //datePicker.locale = NSLocale(localeIdentifier: "zh_CN") as Locale
        // 设置样式，当前设为同时显示日期和时间
        datePicker.datePickerMode = UIDatePickerMode.date
        datePicker.frame = CGRect(x: 0, y: 0, width: alertController.view.bounds.size.width, height: 230)
        // 设置默认时间
        datePicker.date = NSDate() as Date
        // 响应事件（只要滚轮变化就会触发）
        // datePicker.addTarget(self, action:Selector("datePickerValueChange:"), forControlEvents: UIControlEvents.ValueChanged)
        alertController.addAction(UIAlertAction(title: "determine", style: UIAlertActionStyle.default){
            (alertAction)->Void in
            let dformatter = DateFormatter()
            dformatter.dateFormat = "yyyy-MM-dd"
            // 使用日期格式器格式化日期、时间
            let datestr = dformatter.string(from: datePicker.date)
            self.startDateLabel.text = datestr
            print("date select: \(datestr)")
        })
        alertController.addAction(UIAlertAction(title: "cancel", style: UIAlertActionStyle.cancel,handler:nil))
        
        alertController.view.addSubview(datePicker)
        
        self.present(alertController, animated: true, completion: nil)
    }
    
    
    
    func setPieChart(dataPoints: [String], values: [Double], pieChart: PieChartView) {
        var dataEntries: [ChartDataEntry] = []
        for i in 0..<dataPoints.count {
            let entry = PieChartDataEntry(value: values[i], label: "\(dataPoints[i])") //设置数据 title和对应的值
            
            dataEntries.append(entry)
        }
        
        
        let pichartDataSet = PieChartDataSet(values: dataEntries, label: "") //设置表示
        //设置饼状图字体配置
        setPieChartDataSetConfig(pichartDataSet: pichartDataSet)
        
        let pieChartData = PieChartData(dataSet: pichartDataSet)
        //设置饼状图字体样式
        setPieChartDataConfig(pieChartData: pieChartData)
        pieChart.data = pieChartData //将配置及数据添加到表中
        
        //设置饼状图样式
        setDrawHoleState(pieView: pieChart)
        
        var colors: [UIColor] = []
        for i in 0..<dataPoints.count {
            colors.append(self.colors[i%(self.colors.count)])
        }
        pichartDataSet.colors = colors//设置区块颜色
    }
    
   
    
    //设置饼状图字体配置
    func setPieChartDataSetConfig(pichartDataSet: PieChartDataSet){
        pichartDataSet.sliceSpace = 0 //相邻区块之间的间距
        pichartDataSet.selectionShift = 8 //选中区块时, 放大的半径
        pichartDataSet.xValuePosition = .insideSlice //名称位置
        pichartDataSet.yValuePosition = .outsideSlice //数据位置
        //数据与区块之间的用于指示的折线样式
        pichartDataSet.valueLinePart1OffsetPercentage = 0.85 //折线中第一段起始位置相对于区块的偏移量, 数值越大, 折线距离区块越远
        pichartDataSet.valueLinePart1Length = 0.5 //折线中第一段长度占比
        pichartDataSet.valueLinePart2Length = 0.4 //折线中第二段长度最大占比
        pichartDataSet.valueLineWidth = 1 //折线的粗细
        pichartDataSet.valueLineColor = UIColor.gray //折线颜色
        
    }
    
    //设置饼状图字体样式
    func setPieChartDataConfig(pieChartData: PieChartData){
        pieChartData.setValueFormatter(DigitValueFormatter())//设置百分比
        pieChartData.setValueTextColor(UIColor.gray) //字体颜色为灰色
        pieChartData.setValueFont(UIFont.systemFont(ofSize: 10))//字体大小
    }
    
    
    //设置饼状图中心文本
    func setDrawHoleState(pieView: PieChartView){
        ///饼状图距离边缘的间隙
        pieView.setExtraOffsets(left: 30, top: 0, right: 30, bottom: 0)
        //拖拽饼状图后是否有惯性效果
        pieView.dragDecelerationEnabled = false
        //是否显示区块文本
        pieView.drawSlicesUnderHoleEnabled = true
        //是否根据所提供的数据, 将显示数据转换为百分比格式
        pieView.usePercentValuesEnabled = true
        //是否空心圆
        pieView.drawHoleEnabled = false
        
        // 设置饼状图描述
        pieView.chartDescription?.text = ""
        pieView.chartDescription?.font = UIFont.systemFont(ofSize: 10)
        pieView.chartDescription?.textColor = UIColor.gray
        
        // 设置饼状图图例样式
        pieView.legend.maxSizePercent = 1 //图例在饼状图中的大小占比, 这会影响图例的宽高
        pieView.legend.formToTextSpace = 5 //文本间隔
        pieView.legend.font = UIFont.systemFont(ofSize: 10) //字体大小
        pieView.legend.textColor = UIColor.gray //字体颜色
        pieView.legend.verticalAlignment = .bottom //图例在饼状图中的位置
        pieView.legend.form = .circle //图示样式: 方形、线条、圆形
        pieView.legend.formSize = 8 //图示大小
        pieView.legend.orientation = .horizontal
        pieView.legend.horizontalAlignment = .center
        
        pieView.setNeedsDisplay()
    }
    
    
    
    
    func setCharts() {
        
        barChart = BarChartView.init(frame: CGRect.init(x: 0, y: 0, width: scrrenWidth, height: 300))
        barChart.backgroundColor = UIColor.white

        scrollView.addSubview(barChart)
        barChart.snp.makeConstraints { (make) in
            make.top.equalTo(currentDateLabel.snp.bottom).offset(10)
            make.left.equalTo(15)
            make.right.equalTo(-15)
            make.centerX.equalTo(self.view)
            make.width.equalTo(scrrenWidth)
            make.height.equalTo(250)
        }
        
        setBarChart(chartView: barChart)
        titles = ["start","delivery","signature","complete"]
        let datas: [Double]   = [1250,1500,915,1050]
        setBarChartData(titleData: titles!, datas: datas, chartView: barChart)
    }
    
    
    func setBarChart(chartView: BarChartView) {
        
        chartView.noDataText = "暂无数据，刷新重试"
        chartView.drawValueAboveBarEnabled =  true
        chartView.drawValueAboveBarEnabled = true;//数值显示在柱形的上面还是下面
        chartView.drawBarShadowEnabled = false;//是否绘制柱形的阴影背景
        chartView.scaleYEnabled = true;//取消Y轴缩放
        chartView.doubleTapToZoomEnabled = false;//取消双击缩放
        chartView.dragEnabled = false;//启用拖拽图表
        
        chartView.chartDescription?.enabled = false
        chartView.pinchZoomEnabled = true
        chartView.setScaleEnabled(false)
        chartView.drawBarShadowEnabled = false
        chartView.drawGridBackgroundEnabled = false
        
        //设置类型试图的对齐方式，右上角
        let legend = chartView.legend
        legend.enabled = true
        legend.horizontalAlignment = .right
        legend.verticalAlignment = .bottom
        legend.orientation = .horizontal
        legend.textColor = UIColor.init(red: 153/255.0, green: 153/255.0, blue: 153/255.0, alpha: 1.0)
        legend.font = UIFont.systemFont(ofSize: 11.0)
        
        //设置x轴的属性，颜色，字体大小等
        let xAxis = chartView.xAxis
        xAxis.labelPosition = .bottom
        xAxis.drawGridLinesEnabled = false
        xAxis.gridColor = UIColor.init(red: 235/255.0, green: 235/255.0, blue: 235/255.0, alpha: 1.0)
        xAxis.axisLineColor = UIColor.init(red: 235/255.0, green: 235/255.0, blue: 235/255.0, alpha: 1.0)
        xAxis.labelTextColor = UIColor.init(red: 153/255.0, green: 153/255.0, blue: 153/255.0, alpha: 1.0)
        xAxis.labelFont = UIFont.systemFont(ofSize: 11.0)
        
        
        //设置y轴的属性,颜色，字体大小等
        chartView.leftAxis.drawGridLinesEnabled = true
        chartView.leftAxis.gridColor = UIColor.init(red: 235/255.0, green: 235/255.0, blue: 235/255.0, alpha: 1.0)
        chartView.leftAxis.axisLineColor = UIColor.init(red: 235/255.0, green: 235/255.0, blue: 235/255.0, alpha: 1.0)
        chartView.leftAxis.labelTextColor = UIColor.init(red: 153/255.0, green: 153/255.0, blue: 153/255.0, alpha: 1.0)
        chartView.rightAxis.drawGridLinesEnabled = false
        chartView.rightAxis.enabled = false
        chartView.leftAxis.axisMinimum = 0.0
        
    }
    
    
    
    func setBarChartData(titleData: [String]!, datas: [Double], chartView: BarChartView) {
        
        var values = [[BarChartDataEntry]]()
        
        for i in 0..<datas.count {
            
            let val = datas[i]
            var value1 = [BarChartDataEntry]()
            value1.append(BarChartDataEntry.init(x: Double(i), yValues: [val]))
            values.append(value1)
        }
        
        if values.count == 0 {
            
            chartView.data = nil
            chartView.data?.notifyDataChanged()
            chartView.notifyDataSetChanged()
            chartView.noDataText = "暂无数据，请重新刷新"
            return
        }
        
        var sets = [BarChartDataSet]()
        for i in 0..<values.count {
            
            var label: String = ""
            if titleData != nil {
                label = titleData[i%titleData.count]
            }
            
            let set1:BarChartDataSet = BarChartDataSet.init(values: values[i], label: label)
            var colors = [NSUIColor]()
            colors.append(self.colors[i%(self.colors.count)])
            set1.colors = colors
            set1.formSize = 8.0
            set1.highlightEnabled = false
            set1.drawValuesEnabled = true
            set1.valueFormatter = self
            set1.valueTextColor = UIColor.init(red: 153/255.0, green: 153/255.0, blue: 153/255.0, alpha: 1.0)
            set1.valueFont = UIFont.systemFont(ofSize: 11.0)
            sets.append(set1)
            
        }
        
        let data = BarChartData.init(dataSets: sets)
        chartView.data  = data
        chartView.xAxis.valueFormatter = self
        chartView.xAxis.labelCount = datas.count
        chartView.fitBars = true
        chartView.barData?.barWidth = 0.35
        chartView.setNeedsLayout()
        
    }
    
    
    func stringForValue(_ value: Double, axis: AxisBase?) -> String {
        
        if axis == barChart.leftAxis {  //y轴
            if value == Double(Int(value)) {
                return "\(Int(value))"
            }else {
                return ""
            }
        } else {    //x轴
            if let titles = titles {
                if Int(value) <= titles.count-1 {
                    return titles[Int(value)]
                }
            }
            return ""
        }
    }
    
    
    
    func stringForValue(_ value: Double, entry: ChartDataEntry, dataSetIndex: Int, viewPortHandler: ViewPortHandler?) -> String {
        return "\(value)"
    }
    
    
    
    
    
    
    
    func jumpToCurrentJob(button : MenuButton) {
        
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let currentJobController = storyboard.instantiateViewController(withIdentifier: "CurrentJobController") as! CurrentJobController
        currentJobController.title = "Current Job"
        self.navigationController?.pushViewController(currentJobController, animated: true)
    }
    
    
    func jumpToOutstangdingJob(button : MenuButton) {
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let outstandingController = storyboard.instantiateViewController(withIdentifier: "OutstandingController") as! OutstandingController
        outstandingController.title = "Outstanging Job"
        self.navigationController?.pushViewController(outstandingController, animated: true)
    }
    
    
    func jumpToHistory(button : MenuButton) {
        let historyController = HistoryController();
        historyController.title = "History"
        self.navigationController?.pushViewController(historyController, animated: true)
    }
    
    
    func jumpToTrack(button : MenuButton) {
        let trackingController = TrackingController();
        trackingController.title = "Tracking"
        self.navigationController?.pushViewController(trackingController, animated: true)
    }
    
    
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }
    
    
    
    func openMenu() {
        DrawerViewController.shareDrawer?.openLeftMenu()
    }
    
    
    override func viewDidAppear(_ animated: Bool) {
        
        scrollView.contentSize.width = scrrenWidth
        scrollView.contentSize.height = scrrenHeight + 710
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    
    func startOrtherPage(controller: UIViewController) {
        self.navigationController?.pushViewController(controller, animated: true)
    }

        
}

class DigitValueFormatter: NSObject, IValueFormatter {
    func stringForValue(_ value: Double, entry: ChartDataEntry, dataSetIndex: Int, viewPortHandler: ViewPortHandler?) -> String {
        let valueWithoutDecimalPart = String(format: "%.2f%%", value)
        return valueWithoutDecimalPart
    }
}
